package com.snail.billing.data;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import android.os.Environment;

public class AccountFile {

	public static final String SNAIL_GAME = "SnailGame";
	public static final String SYSTEM = "System";
	public static final String UUID = "9dcfdcdf-87d1-4323-b3d6-460c53c71426.json";
	public static final String ACCOUNT = "8a908ad6-be75-488a-9242-d251fdb0a71f.json";

	private File fold;
	private File uuidFile;
	private File accountFile;

	public AccountFile() {
		File sdcard = Environment.getExternalStorageDirectory();
		fold = new File(sdcard.getPath() + "/" + SNAIL_GAME + "/" + SYSTEM);
		fold.mkdirs();
		try {
			uuidFile = new File(fold.getPath() + "/" + UUID);
			uuidFile.createNewFile();
			accountFile = new File(fold.getPath() + "/" + ACCOUNT);
			accountFile.createNewFile();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static boolean sdcardExist() {
		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
	}

	public String getUUID() {
		if (sdcardExist()) {
			try {
				FileReader fileReader = new FileReader(uuidFile);
				StringBuilder builder = new StringBuilder();
				char[] buffer = new char[1024];
				int length = 0;
				while ((length = fileReader.read(buffer)) != -1) {
					builder.append(buffer, 0, length);
				}
				fileReader.close();
				return builder.toString();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "";
	}

	public void setUUID(String uuid) {
		if (sdcardExist()) {
			try {
				FileWriter fileWriter = new FileWriter(uuidFile);
				fileWriter.write(uuid);
				fileWriter.flush();
				fileWriter.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public String getAccountJson() {
		if (sdcardExist()) {
			try {
				FileReader fileReader = new FileReader(accountFile);
				StringBuilder builder = new StringBuilder();
				char[] buffer = new char[1024];
				int length = 0;
				while ((length = fileReader.read(buffer)) != -1) {
					builder.append(buffer, 0, length);
				}
				fileReader.close();
				return builder.toString();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "";
	}

	public void setAccountJson(String randomAccountJson) {
		if (sdcardExist()) {
			try {
				FileWriter fileWriter = new FileWriter(accountFile);
				fileWriter.write(randomAccountJson);
				fileWriter.flush();
				fileWriter.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
